# -*- coding: utf-8 -*-
# appengine imports
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext.webapp import template
from django.utils import simplejson as json

#python imports
import cgi, sys, random, hashlib, hmac, base64, os
#from datetime import datetime

#local imports
from baserequesthandler import BaseRequestHandler
from quizz.models import QAufgabe 
#from benutzer.models.schueler import Schueler, Besucher

from einstellungen import APPLICATION_HOST

#todo: memcache irgendwie einbauen?????


class Handler(BaseRequestHandler):
  def get(self,akey):
    qaufgabe = QAufgabe.gql('where akey = :1 ', akey).get()
    if qaufgabe is not None:
      redirect = "http://%s/video/lsg/%s" % (APPLICATION_HOST,akey)
      aaki = 'AKIAJXJGD5SOPYW5E7VA'
      asak = 'UcNbcBgYlwshKwMgiwgMEpRFPyrj2RlF8RGjmr2D'

      policy_document = """
       {"expiration": "2011-01-01T00:00:00Z",
        "conditions": [ 
            {"x-amz-meta-akey": "%s"},
            {"bucket": "leonanachhilfe"}, 
            ["starts-with", "$key", "mathevideos/%s.flv"],
            {"acl": "public-read"},
            {"redirect": "%s"},
            ["starts-with", "$Content-Type", "video/x-flv"],
            ["starts-with", "$Content-Disposition", "attachment"],
              ["content-length-range", 0, 204857600]
             ]
            }
            """ % (akey,akey, redirect)

      policy = base64.b64encode(policy_document)
      signature = base64.b64encode(
             hmac.new(asak, policy, hashlib.sha1).digest())
      template_values = {
        'application_host':APPLICATION_HOST,
        'aaki' : aaki,
        'akey' : akey,
        'redirect' : redirect,
        'signature': signature,
        'policy' : policy
      }
      directory = os.path.dirname(__file__).replace('/video','')
      path = os.path.join(directory, os.path.join('templates', 'video/hochladen.html'))
      html = template.render(path, template_values)
      self.response.out.write(html)

      return

    else: # es gibt keine solche Quizz-Aufgabe, weg damit
      self.response.out.write(akey)
      #self.redirect('/')
      return

